﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace hkfin
{
    public enum county
    {
        北仑区 = 330206,
        慈溪市 = 330282,
        奉化市 = 330283,
        海曙区 = 330203,
        江北区 = 330205,
       江东区= 330204,
       宁海县 = 330226,
       象山县 = 330225,
       鄞州区 = 330212,
       余姚市 = 330281,
       镇海区 = 330211
    }
  public  struct orgcodestruct
    {
        public string orgCode;
      public string partyName;
      
    }
    public partial class Form1 : Form
    {
         public static List<DJ_BDXX> nowdata= new List<DJ_BDXX>();
        public static CookieContainer SCookieContainer = new CookieContainer();
        public static List<Cookie> LsCookies=new List<Cookie>();
        public static string policyactionVehiclePolicyd = "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d";

        public static string partyactionCustomerActionddsIddsCustomer =
            "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer";
        public static string svrrul = Properties.Settings.Default.svrurl.ToString();
        public static string orgCode = "133006";
        public static string data0102 = "";
           public static List<orgcodestruct> OrgcodeList=    new List<orgcodestruct>();
           public static List<orgcodestruct> BxgsList = new List<orgcodestruct>();
           public static Hashtable employeeCodeList = new Hashtable();
           public static string data0201 = "A1253304";
        public static string agreementCode = "";
        public static string agreementName = "";
        public static string chaxun = "";
        public static hkfinsjkDataContext l = new hkfinsjkDataContext();
            public Form1()
        {
            InitializeComponent();
                textBox7.Text =
                    ConfigurationManager.ConnectionStrings["hkfin.Properties.Settings.HLBXConnectionString"]
                        .ConnectionString.ToString();
                dataGridView1.AutoGenerateColumns = true;
        }
            public static string ToUnicode(string str)
            {
                byte[] bts = Encoding.Unicode.GetBytes(str);
                string r = "";
                for (int i = 0; i < bts.Length; i += 2) r += "\\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
                return r;
            }
            public static string ToGB2312(string str)
            {
                string r = "";
                MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                byte[] bts = new byte[2];
                foreach (Match m in mc)
                {
                    bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
                    bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
                    r += Encoding.Unicode.GetString(bts);
                }
                return r;
            }
        private void button1_Click(object sender, EventArgs e)
        {
            getlogin();
            string svr = "http://core.hkfin.com/ISCS/dorado/view-service";
            string g = "http://core.hkfin.com/ISCS/login.action.main.d";
          //  richTextBox2.Text += cltp(svr, richTextBox3.Text, "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer");
        string s0101o=cltpjs(svr, Properties.Settings.Default.s0101, "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
            string pattern1 = ",\"orgCode\":\"([^\"]+)\",\"partyName\":\"([^\"]+)\",";
            string s0101om = "";
            MatchCollection match = Regex.Matches(s0101o, pattern1);
            foreach (Match match1 in match)
            {
               
                s0101om +="得到的orgcode是:"+ match1.Groups[1].Value+"?";
                s0101om += "得到的orgcode是:" + match1.Groups[2].Value.ToString() + "?" + "值:" + ToGB2312(match1.Groups[2].Value).ToString();
                OrgcodeList.Add(new orgcodestruct() { orgCode = match1.Groups[1].Value.ToString(), partyName = ToGB2312(match1.Groups[2].Value).ToString() });
            }
            
            richTextBox2.Text += s0101o + s0101om;
            string s0102o = cltpjs(svr, Properties.Settings.Default.s0102, "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
            string p0102 = "data\":\"(\\d+)\"";
            Match m0102=  Regex.Match(s0102o, p0102);
            data0102 = m0102.Groups[1].ToString();
            richTextBox2.Text +="得到的vehono是:"+ data0102;
            string s0201 = cltpjs(svr, Properties.Settings.Default.s0201, "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
            string p0201="insurerCode\":\"([^\"]+)\",\"insurerName\":\"([^\"]+)\"";
            MatchCollection match0201 = Regex.Matches(s0201, p0201);
            string s0101om2 = "";
            foreach (Match match1 in match0201)
            {

                s0101om2 += "得到的保险公司编号insurercode是:" + match1.Groups[1].Value + "?";
                s0101om2 += "得到的保险公司名insurerName是:" + match1.Groups[2].Value.ToString() + "?";
                BxgsList.Add(new orgcodestruct() { orgCode = match1.Groups[1].Value.ToString(), partyName = ToGB2312(match1.Groups[2].Value).ToString() });
            }
            richTextBox2.Text += s0101om2;
            string s0202 = cltpxml(svr, Properties.Settings.Default.s0202, "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
            string p0202 ="agreementId\":(\\d+),\"agreementCode\":\"([^\"]+)\",\"agreementName\":\"([^\"]+)\",\"agreementType\":null,\"agreementKind\":null,\"orgCode\":\"133006\",\"signDate\":\"([^\"]+)\",\"startDate\":\"([^\"]+)\",\"endDate\":\"([^\"]+)\",\"period\":null,\"payType\":\"5\",\"signatory\":\"([^\"]+)\",\"address\":null,\"isContinue\":null,\"remarks\":null,\"status\":\"2\",\"verifyStatus\":\"1\",\"insurerCode\":\"([^\"]+)\",\"insurerAgreementCode\":\"([^\"]+)\"";
            Match match0202 = Regex.Match(s0202, p0202);


            agreementCode= match0202.Groups[2].Value;
            agreementName="2014"+ToGB2312( match0202.Groups[3].Value.ToString());
              //  BxgsList.Add(new orgcodestruct() { orgCode = match1.Groups[1].Value.ToString(), partyName = ToGB2312(match1.Groups[2].Value).ToString() });

            richTextBox2.Text += "得到的协议号agreementcode是:" + agreementCode + "得到的协议名agreementname是:" + agreementName;
            string s0301 = cltpxml(svr, Properties.Settings.Default.s0301, "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
            string p0301 = "employeeCode\":\"([^\"]+)\",\"employeeName\":\"([^\"]+)\"";
            MatchCollection match0301 = Regex.Matches(s0301, p0301);
            foreach (Match match1 in match0301)
            {

                s0101om += match1.Groups[1].Value + "?";
                s0101om += match1.Groups[2].Value.ToString() + "?";
                //BxgsList.Add(new orgcodestruct() { orgCode = match1.Groups[1].Value.ToString(), partyName =  match1.Groups[1].Value.ToString() });
                employeeCodeList.Add(match1.Groups[1].Value.ToString(), match1.Groups[2].Value.ToString());
            }
            richTextBox2.Text += s0101om;
            string s0401input = Properties.Settings.Default.s0401.Replace("enurlout",
             "马建平");
                   //     " Microsoft.JScript.GlobalObject.encodeURI("马建平")
            string s0401 = cltpxmlutf8(svr, Properties.Settings.Default.s0402, "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer");
            richTextBox2.Text += s0401;
           /* string lasta =
                Properties.Settings.Default.last.Replace("parta", "马建平")
                    .Replace("partb", "浙江省宁波市海曙区百丈路")
                    .Replace("partc", "浙BG900H")
                    .Replace("partd", "东风ZN1022U2N多用途货车")
                    .Replace("partf", agreementName).Replace("m0102", data0102)
                    .ToString();*/
            string lasta = Properties.Settings.Default.lastd.Replace("partf", agreementName).Replace("m0102", data0102);
            string lastoutput = cltpjsutf8(svr, lasta, "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
            int a = 0;
            return;

        }

        private void getlogin()
        {
            string orgmm = richTextBox1.Text.ToString();
            string md5out =
                System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(orgmm, "MD5").ToLower();
            richTextBox2.Text = md5out;
            string usernm = textBox2.Text.ToString();
            string pswd =
                System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(textBox3.Text.ToString(),
                    "MD5").ToLower();
            ;
            CookieContainer MyCookieContainer = new CookieContainer();
            string oauth = "http://core.hkfin.com/ISCS/LoginServlet?username=" + usernm + "&password=" + pswd;
            HttpWebRequest http = WebRequest.Create(oauth) as HttpWebRequest;
            http.Referer = "http://core.hkfin.com/ISCS/";
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = MyCookieContainer;
            HttpWebResponse response = http.GetResponse() as HttpWebResponse;


            StreamReader reader = new StreamReader(response.GetResponseStream());

            string org = reader.ReadToEnd().ToString();
            richTextBox2.Text += org;
            foreach (Cookie cke in response.Cookies)
            {
                richTextBox2.Text += cke.Name + cke.Value;
                //  SCookieContainer.Add(cke);
                LsCookies.Add(cke);
            }
        }

        public static string getg(string s)
        {
            HttpWebRequest http = WebRequest.Create(s) as HttpWebRequest;
            http.Referer = "http://core.hkfin.com/ISCS/";
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = SCookieContainer;
            using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)

            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string org = reader.ReadToEnd().ToString();
                    return org;
                }


            }
           
        }

        public static string getp(string s,string data)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(s);
            Encoding encoding = Encoding.UTF8;
            string param = data;
            //encoding.GetBytes(postData);
            byte[] bs = Encoding.UTF8.GetBytes(param);
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "text/xml";
            req.Referer = "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d";
            req.ContentLength = bs.Length;
            req.CookieContainer = SCookieContainer;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                    return responseData;
                }
               // context.Response.Write(responseData);
            }
        }

        public static string cltp(string s, string data,string refr)
        {
            WebClient wc = new WebClient();
            string sc = "";
            foreach (Cookie cke in LsCookies)
            {
                sc += cke.Name + "=" + cke.Value + "; ";
            }
            string sc2 = sc.Trim().TrimEnd(';');
          wc.Headers.Add(HttpRequestHeader.Accept,"*/*");
           wc.Headers.Add(HttpRequestHeader.ContentType,"text/xml");
           wc.Headers.Add(HttpRequestHeader.Referer,refr );
         /*  wc.Headers.Add("Accept-Language:zh-Hans-CN,zh-Hans;q=0.5");
           wc.Headers.Add("Accept-Encoding:gzip, deflate");*/
           wc.Headers.Add(HttpRequestHeader.UserAgent,"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
           wc.Headers.Add(HttpRequestHeader.Host,"core.hkfin.com");
         //  wc.Headers.Add(HttpRequestHeader.ContentLength,"478");
          /* wc.Headers.Add("DNT:1");
           wc.Headers.Add("Connection:Keep-Alive");
           wc.Headers.Add("Cache-Control:no-cache");*/
           
            wc.Headers.Add(HttpRequestHeader.Cookie,sc2);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
        string result=    wc.UploadString(s,"POST",data);
            return result;

        }
        public static string cltpjs(string s, string data, string refr)
        {
            WebClient wc = new WebClient();
            string sc = "";
            foreach (Cookie cke in LsCookies)
            {
                sc += cke.Name + "=" + cke.Value + "; ";
            }
            string sc2 = sc.Trim().TrimEnd(';');
            wc.Headers.Add(HttpRequestHeader.Accept, "*/*");
            wc.Headers.Add(HttpRequestHeader.ContentType, "text/javascript");
            wc.Headers.Add(HttpRequestHeader.Referer, refr);
            /*  wc.Headers.Add("Accept-Language:zh-Hans-CN,zh-Hans;q=0.5");
              wc.Headers.Add("Accept-Encoding:gzip, deflate");*/
            wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
            wc.Headers.Add(HttpRequestHeader.Host, "core.hkfin.com");
            //  wc.Headers.Add(HttpRequestHeader.ContentLength,"478");
            /* wc.Headers.Add("DNT:1");
             wc.Headers.Add("Connection:Keep-Alive");
             wc.Headers.Add("Cache-Control:no-cache");*/

            wc.Headers.Add(HttpRequestHeader.Cookie, sc2);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            string result = wc.UploadString(s, "POST", data);
            return result;

        }
        public static string cltpxml(string s, string data, string refr)
        {
            WebClient wc = new WebClient();
            string sc = "";
            foreach (Cookie cke in LsCookies)
            {
                sc += cke.Name + "=" + cke.Value + "; ";
            }
            string sc2 = sc.Trim().TrimEnd(';');
            wc.Headers.Add(HttpRequestHeader.Accept, "*/*");
            wc.Headers.Add(HttpRequestHeader.ContentType, "text/xml");
            wc.Headers.Add(HttpRequestHeader.Referer, refr);
            /*  wc.Headers.Add("Accept-Language:zh-Hans-CN,zh-Hans;q=0.5");
              wc.Headers.Add("Accept-Encoding:gzip, deflate");*/
            wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
            wc.Headers.Add(HttpRequestHeader.Host, "core.hkfin.com");
            //  wc.Headers.Add(HttpRequestHeader.ContentLength,"478");
            /* wc.Headers.Add("DNT:1");
             wc.Headers.Add("Connection:Keep-Alive");
             wc.Headers.Add("Cache-Control:no-cache");*/

            wc.Headers.Add(HttpRequestHeader.Cookie, sc2);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            string result = wc.UploadString(s, "POST", data);
            
            return result;

        }
        public static string cltpxmlutf8(string s, string data, string refr)
        {
            WebClient wc = new WebClient();
            string sc = "";
            foreach (Cookie cke in LsCookies)
            {
                sc += cke.Name + "=" + cke.Value + "; ";
            }
            string sc2 = sc.Trim().TrimEnd(';');
            wc.Headers.Add(HttpRequestHeader.Accept, "*/*");
            wc.Headers.Add(HttpRequestHeader.ContentType, "text/xml");
            wc.Headers.Add(HttpRequestHeader.Referer, refr);
            /*  wc.Headers.Add("Accept-Language:zh-Hans-CN,zh-Hans;q=0.5");
              wc.Headers.Add("Accept-Encoding:gzip, deflate");*/
            wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
            wc.Headers.Add(HttpRequestHeader.Host, "core.hkfin.com");
            //  wc.Headers.Add(HttpRequestHeader.ContentLength,"478");
            /* wc.Headers.Add("DNT:1");
             wc.Headers.Add("Connection:Keep-Alive");
             wc.Headers.Add("Cache-Control:no-cache");*/

            wc.Headers.Add(HttpRequestHeader.Cookie, sc2);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
           // string result = wc.UploadString(s, "POST", data);
           
                byte[] responseData= wc.UploadData(s, "POST", bytes);
                string result = Encoding.UTF8.GetString(responseData);
            return result;

        }
        public static string cltpjsutf8(string s, string data, string refr)
        {
            WebClient wc = new WebClient();
            string sc = "";
            foreach (Cookie cke in LsCookies)
            {
                sc += cke.Name + "=" + cke.Value + "; ";
            }
            string sc2 = sc.Trim().TrimEnd(';');
            wc.Headers.Add(HttpRequestHeader.Accept, "*/*");
            wc.Headers.Add(HttpRequestHeader.ContentType, "text/javascript");
            wc.Headers.Add(HttpRequestHeader.Referer, refr);
            /*  wc.Headers.Add("Accept-Language:zh-Hans-CN,zh-Hans;q=0.5");
              wc.Headers.Add("Accept-Encoding:gzip, deflate");*/
            wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
            wc.Headers.Add(HttpRequestHeader.Host, "core.hkfin.com");
            //  wc.Headers.Add(HttpRequestHeader.ContentLength,"478");
            /* wc.Headers.Add("DNT:1");
             wc.Headers.Add("Connection:Keep-Alive");
             wc.Headers.Add("Cache-Control:no-cache");*/

            wc.Headers.Add(HttpRequestHeader.Cookie, sc2);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            // string result = wc.UploadString(s, "POST", data);

            byte[] responseData = wc.UploadData(s, "POST", bytes);
            string result = Encoding.UTF8.GetString(responseData);
            return result;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox5.Text = openFileDialog1.FileName.ToString();
                ImportExcel(openFileDialog1.FileName, "[Sheet1$]");
            }
        }
        public void ImportExcel(string ExcelName, string Tablename)
        {
            string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelName + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1';";//连接excel文件的字符串
            if (ExcelName == null)
            {
                return;
            }
            OleDbConnection odcon = new OleDbConnection(strcon);//建立连接
            odcon.Open();//打开连接
            ////循环输出显示到控件中
            //OleDbCommand odc = new OleDbCommand("select * from " + Tablename, odcon);
            //OleDbDataReader dr = odc.ExecuteReader();
            //while (dr.Read())
            //{
            //    ListViewItem item=new ListViewItem (dr[0].ToString());
            //    item.SubItems.Add(dr[1].ToString());
            //    listView1.Items.Add(item);
            //}
            //把数据集dataset放到控件中显示
            OleDbDataAdapter odda = new OleDbDataAdapter("select * from " + Tablename, odcon);
            DataSet ds = new DataSet();
            try
            {
                odda.Fill(ds);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (ds != null)
            {

                this.dataGridView1.DataSource = ds.Tables[0];

            }
            else
            {
                MessageBox.Show("没有数据");
            }
        }
        //添加用户
        private void button3_Click(object sender, EventArgs e)
        {
            getlogin();
            string cusername = "吴成军";
            string sfzhm = "330206195605201434";
            string cusercode;
            addyonghu(  cusername, sfzhm,out cusercode,"海曙区");
        }

        private  void addyonghu(       string cusername,     string sfzhm,out string cusercode,string bbrdz)
        {
            string sfzcode = cltpjs(svrrul, Properties.Settings.Default.sfz01,
                "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer");
            string p0102 = "customerCode\":\"([^\"]+)\"},";
            Match m0102 = Regex.Match(sfzcode, p0102);
            cusercode = m0102.Groups[1].ToString();

            county cy =(county) Enum.Parse(typeof (county), bbrdz) ;
            string sfzaddinput =
                Properties.Settings.Default.sfzadd.Replace("cusercode", cusercode)
                    .Replace("cusername", cusername)
                    .Replace("sfzhm", sfzhm).Replace("330203", ((int) cy).ToString()).Replace("海曙区", bbrdz);
            string sfzaddout = cltpjsutf8(svrrul, sfzaddinput,
                "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer");
            richTextBox2.Text += sfzaddout;
            int a = 0;
        }

        //查询身份证
        private void button4_Click(object sender, EventArgs e)
        {
            /*getlogin();
            string customerCode;
            string realAddressout;
           string sfzhm = "330227197403012014";
            GetValuebyidno(sfzhm,out customerCode, out realAddressout);
            int a = 0;*/
            if (radioButton1.Checked)
            {
                nowdata = nowdata.Where(h => h.BBRMC.Trim() == textBox1.Text.Trim()).ToList();
                dataGridView1.DataSource = nowdata;

            }
            if (radioButton2.Checked)
            {
                nowdata = nowdata.Where(h => h.ZJHM.Trim() == textBox4.Text.Trim()).ToList();
                dataGridView1.DataSource = nowdata;
            }
        }

        private void GetValuebyidno( string sfzhm,out string customerCode, out string realAddressout)
        {
            
            string querysfz = Properties.Settings.Default.querysfz.Replace("sfzhm", sfzhm.Trim());
            string sfzqout = cltpxml(svrrul, querysfz,
                "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer");
            richTextBox2.Text += sfzqout;
            string pcustomerCode = "customerCode\":\"(\\d+)\"";
            Match mcustomerCode = Regex.Match(sfzqout, pcustomerCode);
            customerCode = mcustomerCode.Groups[1].ToString();
            string realAddresscode = "realAddress\":\"([^\"]+)\"";
            Match realAddressCode2 = Regex.Match(sfzqout, realAddresscode);
            realAddressout = ToGB2312(realAddressCode2.Groups[1].ToString());
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string connStr = textBox7.Text;
            SqlConnection conn = new SqlConnection(connStr);
            try
            {
                conn.Open();
                MessageBox.Show("测试连接成功");

            }
            catch (System.Exception ex)
            {
                MessageBox.Show("测试连接失败，原因" + ex.Data.ToString() + ex.Message.ToString());
            }
            finally
            {
                conn.Close();
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
           
            string newName = "hkfin.Properties.Settings.HLBXConnectionString";
            string newConString =textBox7.Text ;
            string newProviderName = "System.Data.SqlClient";
            bool isModified = false;    //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  
            if (ConfigurationManager.ConnectionStrings[newName] != null)
            {
                isModified = true;
            }
            //新建一个连接字符串实例  
            ConnectionStringSettings mySettings =
               new ConnectionStringSettings(newName, newConString, newProviderName);
            // 打开可执行的配置文件*.exe.config  
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // 如果连接串已存在，首先删除它  
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            // 将新的连接串添加到配置文件中.  
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("ConnectionStrings");
            MessageBox.Show("重启程序后应用连接字符串确认");
            this.Close();
            Application.Exit();
        }

        private void button7_Click(object sender, EventArgs e)
        {
           
            nowdata = l.DJ_BDXX.Where(h=>h.ZJHM!=null&h.ZJHM!="").ToList();
            dataGridView1.DataSource =nowdata;
         //   dataGridView1.
        }

        private void button8_Click(object sender, EventArgs e)
        {
            nowdata = nowdata.Where(h => h.BBRLX_DM == "01").ToList();
        }
        public  string getcounty(string sinput)
        {
            if (sinput.IndexOf("海曙")!=-1)
            {
                return "海曙区";
            }
            if (sinput.IndexOf("北仑") != -1)
            {
                return "北仑区";
            }
            if (sinput.IndexOf("镇海") != -1)
            {
                return "镇海区";
            }
            if (sinput.IndexOf("奉化") != -1)
            {
                return "奉化市";
            }
            if (sinput.IndexOf("慈溪") != -1)
            {
                return "慈溪市";
            }
            if (sinput.IndexOf("宁海") != -1)
            {
                return "宁海县";
            }
            if (sinput.IndexOf("江北") != -1)
            {
                return "江北区";
            }
            if (sinput.IndexOf("江东") != -1)
            {
                return "江东区";
            }
            if (sinput.IndexOf("鄞州") != -1)
            {
                return "鄞州区";
            }
            if (sinput.IndexOf("余姚") != -1)
            {
                return "余姚市";
            } if (sinput.IndexOf("象山") != -1)
            {
                return "象山县";
            }
           
            else
            {

                return "海曙区";
            }

        }

        private void button11_Click(object sender, EventArgs e)
        {
            /*  getlogin();
          DJ_BDXX q = l.DJ_BDXX.ToList().ElementAt(3);
            getbysingle(q);*/
            System.Diagnostics.Process.Start("http://core.hkfin.com/ISCS");
        }

        private bool getbysingle(DJ_BDXX q)
        {
            try
  {
	  string customerCode;
	            string realAddressout;
	            string sfzhm = q.ZJHM;
	            GetValuebyidno(sfzhm, out customerCode, out realAddressout);
	            if (customerCode == "")
	            {
	                string cusername = q.BBRMC;
	                // string sfzhm = "330206195605201434";
	                // string cusercode;
	                addyonghu(cusername, sfzhm, out customerCode, getcounty(q.BBRDZ));
	            }
	            richTextBox2.Text += customerCode;
	            string svr = "http://core.hkfin.com/ISCS/dorado/view-service";
	            string g = "http://core.hkfin.com/ISCS/login.action.main.d";
	            //  richTextBox2.Text += cltp(svr, richTextBox3.Text, "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer");
	            string s0101o = cltpjs(svr, Properties.Settings.Default.s0101,
	                "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
	            string pattern1 = ",\"orgCode\":\"([^\"]+)\",\"partyName\":\"([^\"]+)\",";
	            string s0101om = "";
	            MatchCollection match = Regex.Matches(s0101o, pattern1);
	            foreach (Match match1 in match)
	            {
	                s0101om += "得到的orgcode是:" + match1.Groups[1].Value + "?";
	                s0101om += "得到的orgcode是:" + match1.Groups[2].Value.ToString() + "?" + "值:" +
	                           ToGB2312(match1.Groups[2].Value).ToString();
	                OrgcodeList.Add(new orgcodestruct()
	                {
	                    orgCode = match1.Groups[1].Value.ToString(),
	                    partyName = ToGB2312(match1.Groups[2].Value).ToString()
	                });
	            }
	
	            richTextBox2.Text += s0101o + s0101om;
	            string s0102o = cltpjs(svr, Properties.Settings.Default.s0102,
	                "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
	            string p0102 = "data\":\"(\\d+)\"";
	            Match m0102 = Regex.Match(s0102o, p0102);
	            data0102 = m0102.Groups[1].ToString();
	            richTextBox2.Text += "得到的vehono是:" + data0102;
	            string s0201 = cltpjs(svr, Properties.Settings.Default.s0201,
	                "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
	            string p0201 = "insurerCode\":\"([^\"]+)\",\"insurerName\":\"([^\"]+)\"";
	            MatchCollection match0201 = Regex.Matches(s0201, p0201);
	            string s0101om2 = "";
	            foreach (Match match1 in match0201)
	            {
	                s0101om2 += "得到的保险公司编号insurercode是:" + match1.Groups[1].Value + "?";
	                s0101om2 += "得到的保险公司名insurerName是:" + match1.Groups[2].Value.ToString() + "?";
	              /*  BxgsList.Add(new orgcodestruct()
	                {
	                    orgCode = match1.Groups[1].Value.ToString(),
	                    partyName = ToGB2312(match1.Groups[2].Value).ToString()
	                });*/
	            }
	            richTextBox2.Text += s0101om2;
	            string s0202 = cltpxml(svr, Properties.Settings.Default.s0202,
	                "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
	            string p0202 =
	                "agreementId\":(\\d+),\"agreementCode\":\"([^\"]+)\",\"agreementName\":\"([^\"]+)\",\"agreementType\":null,\"agreementKind\":null,\"orgCode\":\"133006\",\"signDate\":\"([^\"]+)\",\"startDate\":\"([^\"]+)\",\"endDate\":\"([^\"]+)\",\"period\":null,\"payType\":\"5\",\"signatory\":\"([^\"]+)\",\"address\":null,\"isContinue\":null,\"remarks\":null,\"status\":\"2\",\"verifyStatus\":\"1\",\"insurerCode\":\"([^\"]+)\",\"insurerAgreementCode\":\"([^\"]+)\"";
	            Match match0202 = Regex.Match(s0202, p0202);
	
	
	            agreementCode = match0202.Groups[2].Value;
	            agreementName = "2014" + ToGB2312(match0202.Groups[3].Value.ToString());
	            //  BxgsList.Add(new orgcodestruct() { orgCode = match1.Groups[1].Value.ToString(), partyName = ToGB2312(match1.Groups[2].Value).ToString() });
	
	            richTextBox2.Text += "得到的协议号agreementcode是:" + agreementCode + "得到的协议名agreementname是:" + agreementName;
	            string s0301 = cltpxml(svr, Properties.Settings.Default.s0301,
	                "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
	            string p0301 = "employeeCode\":\"([^\"]+)\",\"employeeName\":\"([^\"]+)\"";
	            MatchCollection match0301 = Regex.Matches(s0301, p0301);
	            foreach (Match match1 in match0301)
	            {
	                s0101om += match1.Groups[1].Value + "?";
	                s0101om += match1.Groups[2].Value.ToString() + "?";
	                //BxgsList.Add(new orgcodestruct() { orgCode = match1.Groups[1].Value.ToString(), partyName =  match1.Groups[1].Value.ToString() });
	               // employeeCodeList.Add(match1.Groups[1].Value.ToString(), match1.Groups[2].Value.ToString());
	            }
	            richTextBox2.Text += s0101om;
	            string s0401input = Properties.Settings.Default.s0401.Replace("enurlout",
	                "马建平");
	            //     " Microsoft.JScript.GlobalObject.encodeURI("马建平")
	            string s0401 = cltpxmlutf8(svr, Properties.Settings.Default.s0402,
	                "http://core.hkfin.com/ISCS/party.action.CustomerAction.d?dsId=dsCustomer");
	            richTextBox2.Text += s0401;
      string lasta="";
      if (q.XZLX_DM == "01")
      {


         lasta =
              Properties.Settings.Default.trrafictj2.Replace("bdrmc", q.BBRMC.Trim())
                  .Replace("dbrdz", q.BBRDZ.Trim())
                  .Replace("bbrdh", "12345678")
                  .Replace("zjhm", q.ZJHM.Trim())
                  .Replace("pcustomerCode", customerCode.Trim())
                  .Replace("cphm", q.CPHM.Trim())
                  .Replace("cphx", q.CPXH.Trim())
                  .Replace("cjhm", q.CJHM.Trim())
                  .Replace("fdjh", q.FDJH.Trim())
                  .Replace("ccdjrq", q.CCDJRQ.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("newje", q.NEWJE.ToString().Trim())
                  .Replace("cbrq", q.CBRQ.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("yxqq", q.Yxq_q.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("yxqz", q.YXQ_Z.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("pzxh", q.PZXH.Trim())
                  .Replace("bxfje", q.BXFJE.ToString().Trim()).Replace("m0102", data0102)
                  .ToString();
      }
      if (q.XZLX_DM == "02")
      {
          lasta =
              Properties.Settings.Default.businesstj.Replace("bdrmc", q.BBRMC.Trim())
                  .Replace("dbrdz", q.BBRDZ.Trim())
                  .Replace("bbrdh", "12345678")
                  .Replace("zjhm", q.ZJHM.Trim())
                  .Replace("pcustomerCode", customerCode.Trim())
                  .Replace("cphm", q.CPHM.Trim())
                  .Replace("cphx", q.CPXH.Trim())
                  .Replace("cjhm", q.CJHM.Trim())
                  .Replace("fdjh", q.FDJH.Trim())
                  .Replace("ccdjrq", q.CCDJRQ.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("newje", q.NEWJE.ToString().Trim())
                  .Replace("cbrq", q.CBRQ.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("yxqq", q.Yxq_q.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("yxqz", q.YXQ_Z.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ss").Trim())
                  .Replace("pzxh", q.PZXH.Trim())
                  .Replace("bxfje", q.BXFJE.ToString().Trim()).Replace("m0102", data0102).ToString();
      }
      // string lasta = Properties.Settings.Default.lastd.Replace("partf", agreementName).Replace("m0102", data0102);
	            string lastoutput = cltpjsutf8(svr, lasta, "http://core.hkfin.com/ISCS/policy.action.VehiclePolicy.d");
	          //  int a = 0;
      if (lastoutput.IndexOf("entityStates") != -1)
      {
          richTextBox2.Text += lastoutput;
          return true;
      }
                else
                {
                    return false;
                }
  }
  catch (System.Exception ex)
  {
      richTextBox3.Text += ex.Message.ToString();
  	return false;
  }
        }

        private void button9_Click(object sender, EventArgs e)
        {
           /* DJ_BDXX q = l.DJ_BDXX.ToList().ElementAt(2);
            string s = q.CCDJRQ.GetValueOrDefault().ToString("yyyy-MM-ddTHH:mm:ssZ");
            int a = 0;*/
          //  nowdata = l.DJ_BDXX.Where(h => h.ZJHM != null & h.ZJHM != "").ToList();
            nowdata = nowdata.Where(h => h.XZLX_DM == "01").ToList();
            dataGridView1.DataSource = nowdata;
        }

        private void button12_Click(object sender, EventArgs e)
        {
        //   int j = 0;
            getlogin();
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                if (Convert.ToBoolean((dataGridView1.Rows[i].Cells["Column1"] as DataGridViewCheckBoxCell).Value  ))
                {
                 //  j += 1;
                    if (getbysingle(nowdata[i]) )
                    {
                        richTextBox1.Text+="成功第"+i.ToString()+
                        "项";
                    }
                    else
                    {
                        richTextBox3.Text += "失败第" + i.ToString() +
                       "项";
                    }
                   
                }
            }
           // MessageBox.Show(j.ToString());

        }

        private void button10_Click(object sender, EventArgs e)
        {
           // nowdata = l.DJ_BDXX.Where(h => h.ZJHM != null & h.ZJHM != "").ToList();
            nowdata = nowdata.Where(h => h.XZLX_DM == "02").ToList();
            dataGridView1.DataSource = nowdata;
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox c = sender as CheckBox;
            if (c.Checked)
            {
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    (dataGridView1.Rows[i].Cells["Column1"] as DataGridViewCheckBoxCell).Value = true;
                }
            }
            else
            {
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    (dataGridView1.Rows[i].Cells["Column1"] as DataGridViewCheckBoxCell).Value =false;
                }
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
